package org.zebra.web.annotation.validation;

import cn.hutool.core.text.CharSequenceUtil;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @author zhanghongbin
 */
public class StringRangeValidator implements ConstraintValidator<StringRange, String> {
    private boolean notNull;
    private String[] valueArray;

    @Override
    public void initialize(StringRange constraintAnnotation) {
        this.notNull = constraintAnnotation.notNull();
        this.valueArray = constraintAnnotation.value();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        if (CharSequenceUtil.isNotBlank(value)) {
            for (String v : valueArray) {
                if (v.equals(value)) {
                    return true;
                }
            }
            return false;
        }

        if (notNull) {
            return false;
        }
        return true;
    }
}
